package com.bdsoft.auth.Mapper;

import com.bdsoft.auth.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;
import java.util.Map;

@Mapper
public interface LoginMapper {

    /**
     * 查询所有用户（测试用）
     * @return 用户列表
     */
    @Select("SELECT id, username, password, department_id as departmentId, " +
            "email, phone, status, create_time as createTime, update_time as updateTime " +
            "FROM user")
    List<Map<String, Object>> selectUser();

//    /**
//     * 根据用户名查询用户
//     * @param username 用户名
//     * @return 用户对象
//     */
    @Select("SELECT id, username, password, department_id as departmentId, " +
            "email, phone, status, create_time as createTime, update_time as updateTime " +
            "FROM user WHERE username = #{username}")
    User selectByUsername(@Param("username") String username);

    /**
     * 查询用户角色信息（修改后适配String类型ID）
     * @param id 用户ID（String类型）
     * @return 角色信息列表
     */
    @Select("SELECT r.id AS role_id, r.name AS role_name, r.code AS role_code " +
            "FROM user u " +
            "LEFT JOIN user_role ur ON u.id = ur.user_id " +
            "LEFT JOIN role r ON ur.role_id = r.id " +
            "WHERE u.id = #{id}")
    List<Map<String, Object>> selectUserRole(@Param("id") String id);

    /**
     * 新增方法：根据用户ID查询用户基本信息
     * @param id 用户ID（String类型）
     * @return 用户对象
     */
    @Select("SELECT id, username, password, department_id as departmentId, " +
            "email, phone, status, create_time as createTime, update_time as updateTime " +
            "FROM user WHERE id = #{id}")
    User selectById(@Param("id") String id);


    @Select("SELECT \n" +
            "    m.menu_id,\n" +
            "    m.menu_name,\n" +
            "    m.path,\n" +
            "    m.component,\n" +
            "    m.icon,\n" +
            "    m.permission\n" +
            "FROM \n" +
            "    user u\n" +
            "JOIN \n" +
            "    user_role ur ON u.id = ur.user_id\n" +
            "JOIN \n" +
            "    rolemenu rm ON ur.role_id = rm.role_id\n" +
            "JOIN \n" +
            "    menu m ON rm.menu_id = m.menu_id\n" +
            "WHERE \n" +
            "    u.id = #{userId}\n" +
            "    AND m.status = 1  -- 只查询启用的菜单\n" +
            "ORDER BY \n" +
            "    m.sort ASC;")
    List<Map<String,Object>> getpermisstionList(String userId);

    @Select("SELECT DISTINCT r.resource_id FROM user u JOIN user_role ur ON u.id = ur.user_id JOIN roleresource rr ON ur.role_id = rr.role_id JOIN resource r ON rr.resource_id = r.resource_id WHERE u.id = #{userId}")
    List<String> getResourceIdsByUserId(@Param("userId") String userId);
}